package com.chhuang.ewcrm.ctrl;

import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.bean.TableColumnBean;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.dao.WLprCameraDao;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.WLprCamera;
import com.chhuang.ewcrm.string.StringUtil;
import com.chhuang.ewcrm.thread.AddLogThread;
import com.chhuang.ewcrm.utils.IntTextFilter;
import com.chhuang.ewcrm.utils.LengthTextFilter;
import com.github.pagehelper.PageHelper;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXCheckBox;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 车牌识别摄像头配置类
 */
public class LPRCameraController implements InitController {
    private final Logger logger = LoggerFactory.getLogger(LPRCameraController.class);

    @FXML
    private ComboBox<String> cameraBrandComboBox;
    @FXML
    private TextField cameraIpTextField;
    @FXML
    private TextField cameraPortTextField;
    @FXML
    private TextField usernameTextField;
    @FXML
    private TextField passwordTextField;
    @FXML
    private JFXCheckBox enableJFXCheckBox;
    @FXML
    private JFXButton saveJFXButton;
    @FXML
    private JFXButton delJFXButton;
    @FXML
    private TableView<WLprCamera> cameraTableView;

    private WLprCameraDao wLprCameraDao = App.getSession().getMapper(WLprCameraDao.class);

    private QueryBean<WLprCamera> queryBean = new QueryBean<>();

    private TableColumnBean[] tableColumnBeans = {
            new TableColumnBean("ID", "cameraId", false, false),
            new TableColumnBean("品牌", "cameraBrand"),
            new TableColumnBean("摄像头ip","cameraIp", true),
            new TableColumnBean("摄像头端口","cameraPort"),
            new TableColumnBean("用户名","cameraUsername"),
            new TableColumnBean("密码","cameraPassword"),
            new TableColumnBean("是否启用","cameraEnable"){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    if((Boolean)o)return "是"; else return "否";
                }
            },
            new TableColumnBean("修改时间","modifyTime",true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.TIME_FORMAT);
                }
            },
            new TableColumnBean("创建时间","createTime",true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.TIME_FORMAT);
                }
            }
    };

    private final LengthTextFilter lengthTextFilter = new LengthTextFilter();

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //设置编辑区
        cameraBrandComboBox.getItems().addAll("芊熠");
        cameraBrandComboBox.getSelectionModel().select(0);
        cameraIpTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        usernameTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        passwordTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        cameraPortTextField.setTextFormatter(new TextFormatter<String>(new IntTextFilter(5)));

        //设置表格列名
        List<TableColumn<WLprCamera, Object>> tableColumns = new LinkedList<>();
        for (TableColumnBean tb : tableColumnBeans) {
            TableColumn<WLprCamera, Object> tableColumn = new TableColumn<>(tb.getColumnName());
            tableColumn.setCellValueFactory(new PropertyValueFactory<>(tb.getRecordName()));
            tableColumn.setSortable(tb.isSort());
            tableColumn.setVisible(tb.isVisible());
            final TableColumnBean _tb = tb;
            tableColumn.setCellFactory(column -> {
                TableCell<WLprCamera, Object> cell =  new TableCell<>() {
                    @Override
                    protected void updateItem(Object o, boolean b) {
                        super.updateItem(o, b);
                        if(b || o==null)
                            this.setText(null);
                        else
                            this.setText(_tb.format(o));
                    }
                };
                cell.setAlignment(Pos.CENTER);
                return cell;
            });
            tableColumns.add(tableColumn);
        }
        cameraTableView.getColumns().addAll(tableColumns);

        //双击列表中的信息
        cameraTableView.setRowFactory( tv -> {
            TableRow<WLprCamera> row = new TableRow<WLprCamera>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && !row.isEmpty() ) {
                    WLprCamera wCamera = row.getItem();
                    cameraBrandComboBox.setValue(wCamera.getCameraBrand());
                    cameraIpTextField.setText(wCamera.getCameraIp());
                    cameraPortTextField.setText(wCamera.getCameraPort()==null?null:wCamera.getCameraPort().toString());
                    usernameTextField.setText(wCamera.getCameraUsername());
                    passwordTextField.setText(wCamera.getCameraPassword());
                    enableJFXCheckBox.setSelected(wCamera.getCameraEnable());
                }
            });
            return row ;
        });

        //自定义排序

        //获取表格数据
        getTableData();
        //初始化监听
        initListener();
    }

    /**
     * 获取表格数据
     */
    private void getTableData() {
        if(StringUtils.isEmpty(queryBean.getOrderBy())){
            queryBean.setOrderBy("create_time desc");
        }
        PageHelper.orderBy(queryBean.getOrderBy());
        List<WLprCamera> wCameras = wLprCameraDao.query(queryBean.getQuery());

        cameraTableView.getItems().clear();
        if(wCameras!=null && !wCameras.isEmpty())
            cameraTableView.getItems().addAll(wCameras);
//        cameraTableView.setItems(FXCollections.observableList(wCameras));//使用自定义排序就不能用这个方法
    }

    /**
     * 初始化监听
     */
    private void initListener() {
        //添加
        saveJFXButton.setOnAction(event -> {
            String cameraBrand = cameraBrandComboBox.getValue();
            String cameraIp = cameraIpTextField.getText();
            if(StringUtils.isEmpty(cameraIp) || !StringUtil.isIP(cameraIp)){
                return;
            }
            String cameraPortStr = cameraPortTextField.getText();
            if(StringUtils.isEmpty(cameraPortStr)){
                return;
            }
            Short cameraPort = Short.parseShort(cameraPortStr);
            String username = usernameTextField.getText();
            String password = passwordTextField.getText();
            Boolean enable = enableJFXCheckBox.isSelected();

            Date now = new Date();
            WLprCamera wCamera = new WLprCamera();
            wCamera.setCameraIp(cameraIp);
            List<WLprCamera> wCameras = wLprCameraDao.query(wCamera);
            if(wCameras!=null && !wCameras.isEmpty()){//IP存在 修改
                wCamera = wCameras.get(0);
            }else{//IP不存在 添加
                wCamera.setCreateTime(now);
            }
            wCamera.setCameraBrand(cameraBrand);
            wCamera.setCameraPort(cameraPort);
            wCamera.setCameraUsername(username);
            wCamera.setCameraPassword(password);
            wCamera.setCameraEnable(enable);
            wCamera.setModifyTime(now);

            if(StringUtils.isEmpty(wCamera.getCameraId())){//添加
                wLprCameraDao.insert(wCamera);
                new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                        Constants.loginUser.getUsername(),
                        Constants.loginUser.getFullname(),
                        "添加新车牌识别摄像头："+wCamera.toString())).start();
            }else {//修改
                wLprCameraDao.update(wCamera);
                new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                        Constants.loginUser.getUsername(),
                        Constants.loginUser.getFullname(),
                        "修改车牌识别摄像头信息："+wCamera.toString())).start();
            }

            //获取表格数据
            getTableData();
            //清空表单
            resetForm();
        });

        //删除
        delJFXButton.setOnAction(event -> {
            String cameraIp = cameraIpTextField.getText();
            if(StringUtils.isNotEmpty(cameraIp)){
                WLprCamera wCamera = new WLprCamera();
                wCamera.setCameraIp(cameraIp);
                List<WLprCamera> wCameras = wLprCameraDao.query(wCamera);
                if(wCameras!=null && !wCameras.isEmpty()) {//IP存在
                    new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                            Constants.loginUser.getUsername(),
                            Constants.loginUser.getFullname(),
                            "删除车牌识别摄像头信息："+wCameras.get(0).toString())).start();
                    wLprCameraDao.deleteByEntity(wCameras.get(0));
                }
                //获取表格数据
                getTableData();
            }
            //清空表单
            resetForm();
        });
    }

    /**
     * 清空表单
     */
    private void resetForm() {
        cameraBrandComboBox.getSelectionModel().select(0);
        cameraIpTextField.clear();
        cameraPortTextField.clear();
        usernameTextField.clear();
        passwordTextField.clear();
        enableJFXCheckBox.setSelected(false);
    }

    @Override
    public void close() {

    }
}
